package com.jjb.common.task.task;

import com.jjb.common.task.infrastructure.persistence.domainobject.MessageTaskDO;
import com.jjb.common.task.service.TaskService;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecTask {

    private TaskService taskService;
    private ExecutorService executors = Executors.newFixedThreadPool(20);

    public ExecTask(TaskService taskService) {
        this.taskService = taskService;
    }


    public void handler() {
        List<MessageTaskDO> messageTasks = this.taskService.findExec(100);
        if ( ! (messageTasks == null || messageTasks.isEmpty())) {
            CountDownLatch count = new CountDownLatch(messageTasks.size());
            for (MessageTaskDO messageTask : messageTasks) {
                executors.submit(() -> {
                    try {
                        handler(messageTask);
                    }finally {
                        count.countDown();
                    }
                });
            }
            try {count.await();} catch (InterruptedException e) {}
        }
    }

    private void handler(MessageTaskDO messageTask) {
        this.taskService.execById(messageTask.getId());
    }


}
